package dk.android.houseenabler;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.ExpandableListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ExpandableListView;
import android.widget.SimpleExpandableListAdapter;
import dk.android.houseenabler.classes.FileHandle;
import dk.android.houseenabler.classes.HouseEnablerSettings;
import dk.android.houseenabler.models.Answer;
import dk.android.houseenabler.models.AnswerCollection;
import dk.android.houseenabler.models.HouseCollection;

public class ExpandableActivity extends ExpandableListActivity {

	private String[] alphabet = { "a", "b", "c", "d", "e", "f", "g" };
	private String c;
	private HouseCollection houseCollection;
	private AnswerCollection answerCollection;
	private int housePosition = -1;

	

	@SuppressWarnings("unchecked")
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		// Create an array of Strings, that will be put to our ListActivity
		setContentView(R.layout.expandablelist);
		
		//Toast.makeText(this, "Start", Toast.LENGTH_SHORT).show();
		Bundle extras = getIntent().getExtras();
		
		c = extras.getString("category");
		housePosition = extras.getInt("housePosition");

		readAnswerCollection();
		
		SimpleExpandableListAdapter expListAdapter = new SimpleExpandableListAdapter(
				this, createGroupList(), // Creating group List.
				R.layout.group_row, // Group item layout XML.
				new String[] { "Group Item" }, // the key of group item.
				new int[] { R.id.row_name }, // ID of each group item.-Data
												// under the key goes into
												// this TextView.
				createChildList(), // childData describes second-level
									// entries.
				R.layout.child_row, // Layout for sub-level entries(second
									// level).
				new String[] { "Sub Item" }, // Keys in childData maps to
												// display.
				new int[] { R.id.grp_child } // Data under the keys above go
												// into these TextViews.
		){
			@Override
			public View getChildView(final int groupPosition, final int childPosition,
					boolean isLastChild, View convertView, ViewGroup parent) {
				View v = super.getChildView(groupPosition, childPosition,
						isLastChild, convertView, parent);

				if (v != null) {
					
					CheckBox cb = (CheckBox) v.findViewById(R.id.check);
					readAnswerCollection(); 
					if(cb != null) {
						int offset = 0;
						for(int i = 0 ; i < groupPosition ; i++) {
							String s = alphabet[i];
							int id = getResources().getIdentifier(c + s,"array", "dk.android.houseenabler");
							offset += getResources().getStringArray(id).length;
						}
						offset += childPosition;
						
						 Answer answer = ExpandableActivity.this.answerCollection.getAnswer(c.charAt(0), offset);
						boolean checked = false;
						if(answer != null) {
							if(answer.isChecked()) {
								//Toast toast = Toast.makeText(ExpandableActivity.this, "Index: " + offset, 2000);
								//toast.show();
								checked = true;
							}
						}
						cb.setChecked(checked);
					}

					
					//Checked change event on checkbox
					cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
						public void onCheckedChanged(CompoundButton arg0, boolean checked) {
							//The message for the checked checkbox
							//final String value = "Check is "+ checked +" for Checkbox in tab: "+ c + ", on Group: " + groupPosition + ", on Child: " + childPosition;
							
							int offset = 0;
							for(int i = 0 ; i < groupPosition ; i++) {
								String s = alphabet[i];
								int id = getResources().getIdentifier(c + s,"array", "dk.android.houseenabler");
								offset += getResources().getStringArray(id).length;
							}
							offset += childPosition;
							
							Answer answer = ExpandableActivity.this.answerCollection.getAnswer(c.charAt(0), offset);
							if(answer == null) {
							  answer = new Answer();
							}
							
							answer.setChecked(checked);
							//ADDS the question Title to the answer (Used in creation the comments)
							int idTitle = getResources().getIdentifier(c+ alphabet[groupPosition],"array", "dk.android.houseenabler");
							String[] Rchilds = getResources().getStringArray(idTitle);
							answer.setTitle(Rchilds[childPosition]);
							//END ADD title
							answerCollection.addTo(c.charAt(0), offset, answer);
							ExpandableActivity.this.saveCollectionToFile();
							
							//Toast toast = Toast.makeText(ExpandableActivity.this, "Index: " + offset, 2000);
						}
					});
				}

				return v;
			}
		};
		setListAdapter(expListAdapter); // setting the adapter in the list.

	}
	@Override
	protected void onResume() {
	 super.onResume();
	 // The activity has become visible (it is now "resumed").
	 readAnswerCollection();
	}


	private void readAnswerCollection() {
		FileHandle fh = new FileHandle(); 
		HouseCollection hc = (HouseCollection)fh.readObjectFromStorage(HouseEnablerSettings.HOUSESCOLLECTIONFILENAME);
        if(hc != null) {
        	this.houseCollection = hc;
        }
        
        this.answerCollection = this.houseCollection.getHouse(housePosition).getAnswers();
        if(this.answerCollection == null) {
        	System.out.println("ER NULL!!!");
        }
	}
	
	private void saveCollectionToFile() {
		
		this.houseCollection.getHouse(housePosition).setAnswers(this.answerCollection);
		
		FileHandle fh = new FileHandle();
		fh.writeObjectToStorage(HouseEnablerSettings.HOUSESCOLLECTIONFILENAME, this.houseCollection);
		
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private List createGroupList() {
		ArrayList result = new ArrayList();
		for (String s : alphabet) { // 15 groups........

			HashMap m = new HashMap();
			int id = getResources().getIdentifier(c + s + "_name",
					"string", "dk.android.houseenabler");
			
			if (id != 0) {
				getResources().getText(id);
				m.put("Group Item", getResources().getText(id)); // the key and it's value.
			} else {
				return result;
			}
			result.add(m);
		}
		return (List) result;
	}


	@SuppressWarnings({ "rawtypes", "unchecked" })
	private List createChildList() {
		
		ArrayList<ArrayList> result = new ArrayList<ArrayList>();
		for (String s : alphabet) {
			if (getResources().getIdentifier(c + s + "_name", "string",
					"dk.android.houseenabler") != 0) {
				int id = getResources().getIdentifier(c+ s,"array", "dk.android.houseenabler");
				
				String[] Rchilds = getResources().getStringArray(id);
				ArrayList<HashMap> secList = new ArrayList<HashMap>();
				for(String d : Rchilds)
				{
					HashMap childs = new HashMap();
					childs.put("Sub Item", d);
					secList.add(childs);
				}
				result.add(secList);
			}
			else
			{
				return result;
			}
			
		}
		
		return result;

	}

	
	@Override
	public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) 
	{

		
		
		
		//TESTING
		Intent intentDesc = new Intent().setClass(this, DescriptionActivity.class);

		//GET TITLE
		int idTitle = getResources().getIdentifier(c+ alphabet[groupPosition],"array", "dk.android.houseenabler");
		String[] Rchilds = getResources().getStringArray(idTitle);
		intentDesc.putExtra("title", Rchilds[childPosition]);
		
		//GET Desctiption
		int idDesc = getResources().getIdentifier(c+ alphabet[groupPosition]+"_desc","array", "dk.android.houseenabler");
		String[] RDesc = getResources().getStringArray(idDesc);
		intentDesc.putExtra("description", RDesc[childPosition]);
		
		//Get House Catagory
		String catagory = getIntent().getExtras().getString("category");
		intentDesc.putExtra("category", catagory);
		
		//GET House Title
		String houseTitle = getIntent().getExtras().getString("houseTitle");
		intentDesc.putExtra("houseTitle",houseTitle);
		
		//GET Question Possition
		intentDesc.putExtra("c", c);
		intentDesc.putExtra("childPosition", childPosition);
		intentDesc.putExtra("groupPosition",groupPosition);
		
		//GET House Position
		int housePosition = getIntent().getIntExtra("housePosition", -1);
		intentDesc.putExtra("housePosition", housePosition);
		
		
		startActivity(intentDesc);
		return true;
	}
	 @Override
	    public boolean onCreateOptionsMenu(Menu menu) {
	        MenuInflater inflater = getMenuInflater();
	        inflater.inflate(R.menu.menu, menu);
	        return true;
	    }

	    @Override
	    public boolean onOptionsItemSelected(MenuItem item) {
	        switch (item.getItemId()) {
	            case R.id.icon_home:    
	            	finish();
	            	//Toast.makeText(this, "You pressed the Back!", Toast.LENGTH_LONG).show();
	                                break;
	            case R.id.icon_export:
	            	Intent intentExport = new Intent().setClass(ExpandableActivity.this, SendMailActivity.class);
	            	startActivity(intentExport);
	            	//Toast.makeText(this, "You pressed the Export!", Toast.LENGTH_LONG).show();
	                                break;
	        }
	        return true;
	    }


}
